#include "common_api.h"
#include "FreeRTOS.h"
#include "task.h"
#include "usart.h"
#include "semphr.h"

void CH_Init(void)
{
}
//void CA_Printf();
void CH_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
	HAL_GPIO_TogglePin(GPIOx,GPIO_Pin);
}

void CH_Delay(u32 delay)
{
	HAL_Delay(delay);
}

GPIO_PinState read_pin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
	return HAL_GPIO_ReadPin(GPIOx,GPIO_Pin);
}

void write_pin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
{
	HAL_GPIO_WritePin(GPIOx,GPIO_Pin,PinState);
}

__align(8) char Usart_TxBuff[USART_TXBUFF_SIZE];  

void CH_Printf(char* fmt,...)
{
	int i,length;
	extern SemaphoreHandle_t printMutex;
	xSemaphoreTake(printMutex, portMAX_DELAY);

	memset(Usart_TxBuff,0,sizeof(Usart_TxBuff));
	
	va_list ap;
	va_start(ap,fmt);
	vsprintf(Usart_TxBuff,fmt,ap);
	va_end(ap);
	
	length = strlen((const char *)Usart_TxBuff);
	while((PRINTF_USERT->SR&0X40)==0);
	for(i = 0;i < length;i ++)
	{			
		PRINTF_USERT->DR = Usart_TxBuff[i];
		while((PRINTF_USERT->SR&0X40)==0);	
	}
	
	xSemaphoreGive(printMutex);
}

__align(8) char Usart_TxBuff2[USART_TXBUFF_SIZE];  
void CH_UsartPrintf(USART_TypeDef * usart,char * fmt,...)
{
	int i,length;
	memset(Usart_TxBuff,0,sizeof(Usart_TxBuff2));
	
	va_list ap;
	va_start(ap,fmt);
	vsprintf(Usart_TxBuff,fmt,ap);
	va_end(ap);
	
	length = strlen((const char *)Usart_TxBuff2);
	while((usart->SR&0X40)==0);
	for(i = 0;i < length;i ++)
	{			
		usart->DR = Usart_TxBuff2[i];
		while((usart->SR&0X40)==0);	
	}
}

void CH_UsartSendString(USART_TypeDef * usart,u8 * data)
{
//	int	i;
//	while((usart->SR&0X40)==0);
//	for(i = 1;i <= data[0];i ++)
//	{			
//		usart->DR = data[i];
//		while((usart->SR&0X40)==0);	
//	}
	
	int	i;	
	while((USART2->SR&0X40)==0);
	for(i = 1;i <= (data[0]*256+data[1]);i ++){			
		USART2->DR = data[i+1];
		while((USART2->SR&0X40)==0);	
	}
}

void CH_UsartSendBuf(USART_TypeDef * usart,u8 * buf,u16 len)
{
	while((usart->SR&0X40)==0);
	for(u16 i = 0;i <= len;i ++)
	{			
		usart->DR = buf[i];
		while((usart->SR&0X40)==0);	
	}
}

void CH_UsartSendByte(USART_TypeDef * usart,u8 byte)
{
	while((usart->SR&0X40)==0);
	usart->DR = byte;
	while((usart->SR&0X40)==0);	
}

u16 CH_SwitchU16(u16 s)
{
	return ((s & 0x00FF) << 8) | ((s & 0xFF00) >> 8);
}


//2、32bit大小端转换

u32 CH_SwitchU32(u32 i)
{
	return ((i & 0x000000FF) << 24) | ((i & 0x0000FF00) << 8) | ((i & 0x00FF0000) >> 8) | ((i & 0xFF000000) >> 24);
}

//关闭所有中断
void INTX_DISABLE(void)
{		  
	__ASM volatile("cpsid i");
}
//开启所有中断
void INTX_ENABLE(void)
{
	__ASM volatile("cpsie i");		  
}